package com.weetop.akly.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.weetop.akly.R;
import com.weetop.akly.activity.login.LoginActivity;
import com.weetop.akly.apiUtils.ApiRetrofit;
import com.weetop.akly.apiUtils.ApiServer;
import com.weetop.akly.appConfig.MyApplication;
import com.weetop.akly.base.mvp.BaseModel;
import com.weetop.akly.base.mvp.BaseObserver;
import com.weetop.akly.base.mvp.BasePresenter;
import com.weetop.akly.base.mvp.BaseView;
import com.weetop.akly.bean.PostMessage;
import com.weetop.akly.utils.BaseUtils;
import com.weetop.akly.utils.EventBusUtil;
import com.weetop.akly.utils.MMKVUtils;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.schedulers.Schedulers;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;

/**
 * File descripition: activity基类
 * <p>
 *
 * @author lp
 * @date 2018/5/16
 */
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity implements BaseView {
    protected final String TAG = this.getClass().getSimpleName();
    public Context mContext;
    protected P mPresenter;
    public MyApplication myApplication;
    protected Activity mActivity;
    protected boolean isClear=false;
    protected int pageNum=1;
    protected int pageSize=15;
    protected abstract P createPresenter();
    protected ApiServer apiServer = ApiRetrofit.getInstance().getApiService();
    private CompositeDisposable compositeDisposable;

    public void addDisposable(Observable<?> observable, BaseObserver observer) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(observer));
    }

    //错误提示框  警告框  成功提示框 加载进度框 （只是提供个案例 可自定义）
    protected QMUITipDialog tipDialog;
//
//    @Override
//    protected boolean translucentFull() {
//        return true;
//    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        myApplication = (MyApplication) getApplication();
        mActivity = BaseActivity.this;
        mPresenter = createPresenter();
        if (isRegisterEventBus()) {
            EventBusUtil.register(this);
        }
        setTitleBarStytle(mActivity);
    }

    protected void setToolBar(Toolbar toolbar) {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    protected void setTitleInfo(String text) {
        RelativeLayout rl_back=findViewById(R.id.rl_back);
        TextView tv_data_title=findViewById(R.id.tv_data_title);
        rl_back.setOnClickListener(v -> {finish();});
        tv_data_title.setText(text);
        QMUIStatusBarHelper.setStatusBarLightMode(this);
    }

    protected void setToolBar(String ceterText,String rightText) {
        Toolbar toolbar =findViewById(R.id.toolbar);
        TextView tv_tl_title= findViewById(R.id.tv_tl_title);
        TextView tv_tl_right= findViewById(R.id.tv_tl_right);

        tv_tl_title.setText(ceterText);
        tv_tl_right.setText(rightText);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


    protected void setToolBar(String ceterText, String rightText, View.OnClickListener clickListener) {
        Toolbar toolbar =findViewById(R.id.toolbar);
        TextView tv_tl_title= findViewById(R.id.tv_tl_title);
        TextView tv_tl_right= findViewById(R.id.tv_tl_right);

        tv_tl_title.setText(ceterText);
        tv_tl_right.setText(rightText);

        tv_tl_right.setOnClickListener(clickListener);

        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }



    protected void setTitleBarStytle(Activity activity) {
        BaseUtils.setTitleBarColor(activity);
        QMUIStatusBarHelper.setStatusBarLightMode(activity);
    }
    @Override
    public Resources getResources() {
        Resources res =  super.getResources();
        Configuration config=new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config,res.getDisplayMetrics() );
        return res;
    }


    /**
     * 是否注册事件分发
     *
     * @return true绑定EventBus事件分发，默认不绑定，子类需要绑定的话复写此方法返回true.
     */
    protected boolean isRegisterEventBus() {
        return false;
    }

    /**
     *  接口加载
     * @return
     */
    protected boolean isShowNetLoading() {
        return true;
    }
    protected void showDialog(String str) {
        if (str.equals("")) {
            tipDialog = new QMUITipDialog.Builder(mActivity)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .create();
        } else {
            tipDialog = new QMUITipDialog.Builder(mActivity)
                    .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                    .setTipWord(str)
                    .create();
        }

        tipDialog.show();
    }


    protected void dissmissDialog() {
        if (tipDialog != null)
            tipDialog.dismiss();
    }

    @Override
    public void showError(String msg) {
         ToastUtils.showShort(msg);
    }

    @Override
    public void showLoading() {
        if (isShowNetLoading())
            showDialog("请稍后");
    }

    @Override
    public void hideLoading() {
        if (isShowNetLoading())
            dissmissDialog();
    }

    @Override
    public void onErrorCode(BaseModel model) {
        if (model != null){
            if (model.getCode()==-888){
                final AlertDialog.Builder normalDialog =
                        new AlertDialog.Builder(BaseActivity.this);
                normalDialog.setTitle("提示");
                normalDialog.setMessage("账号已在其他地方登陆");
                normalDialog.setPositiveButton("重新登陆",(dialog, which) -> {
                    dialog.dismiss();
                });
                normalDialog.setOnDismissListener(dialog -> {
                    MMKVUtils.removeUserToken();
                    MMKVUtils.removeRyToken();
                    RongIM.getInstance().logout();
                    RongUserInfoManager.getInstance().uninit();
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivity(intent);
                    ActivityUtils.finishAllActivitiesExceptNewest();
                    mActivity.finish();
                });
                normalDialog.show();
            }else {
               // ToastUtils.showShort(model.getMsg());
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        if (isRegisterEventBus()) {
            EventBusUtil.unregister(this);
        }
    }

    /**
     * 接收到分发到事件
     *
     * @param event 事件
     */
    protected void receiveEvent(PostMessage event) {

    }

    /**
     * 接受到分发的粘性事件
     *
     * @param event 粘性事件
     */
    protected void receiveStickyEvent(PostMessage event) {

    }


    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onEventBusCome(PostMessage event) {
        if (event != null) {
            receiveEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING, sticky = true)
    public void onStickyEventBusCome(PostMessage event) {
        if (event != null) {
            receiveStickyEvent(event);
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        // 进行数据处理

        super.onConfigurationChanged(newConfig);

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        // 保存数据
    }

}
